var express = require('express')
var log = require('morgan')
var bodyParser = require('body-parser')
var app = express()
var cookieParser = require('cookie-parser')

app.use(log('dev'))
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static('./public'))

var template = require('art-template')
template.config('base', '');
template.config('extname', '.html');
app.engine('.html', template.__express);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

const userDate = [
    { userName: 'admin', pwd: 'admin' }
]

app.post('/admin/login', (req, res) => {
    var userName = req.body.userName
    var userPwd = req.body.userPwd

    var user = userDate.find(item => {
        return item.userName == userName
    })
    if (user) {
        if (user.pwd == userPwd) {
            res.cookie('adminUserName', userName, { path: '/' })
            res.json({
                status: 'y',
                msg: '登陆成功'
            })
        } else {
            res.json({
                status: 'n',
                msg: '用户密码错误'
            })
        }
    } else {
        res.json({
            status: 'n',
            msg: '用户信息不存在'
        })
    }
})

app.all('/admin/*', (req, res, next) => {
    if (req.cookies.adminUserName) {
        next()
    } else {
        res.redirect('/login.html')
    }
})

app.get('/admin/index', (req, res) => {
    res.render('admin/index')
})

app.use('/admin/blog_type', require('./routes/admin/blog_type_controller'))
app.use('/admin/blog', require('./routes/admin/blog_controller'))
app.use('/user', require('./routes/user/index_controller'))

app.listen('3000', () => {
    console.log('风萧萧兮易水寒,壮士一去不复返,3000端口已运行')
})